import { defineStore } from 'pinia'
import { authApi } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: (() => {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        return userInfoStr && userInfoStr !== 'undefined' ? JSON.parse(userInfoStr) : {}
      } catch (error) {
        console.error('解析用户信息失败:', error)
        return {}
      }
    })(),
    isLoggedIn: !!localStorage.getItem('token')
  }),

  getters: {
    userId: (state) => state.userInfo.userId || 0,
    username: (state) => state.userInfo.username || '',
    realName: (state) => state.userInfo.realName || '',
    gender: (state) => state.userInfo.gender || 0,
    birthDate: (state) => state.userInfo.birthDate || '',
    phone: (state) => state.userInfo.phone || '',
    email: (state) => state.userInfo.email || '',
    height: (state) => state.userInfo.height || null,
    targetWeight: (state) => state.userInfo.targetWeight || null,
    healthGoal: (state) => state.userInfo.healthGoal || '',
    healthNotes: (state) => state.userInfo.healthNotes || ''
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await authApi.login(loginForm)
        const { token, userId, username } = response
        
        this.token = token
        this.userInfo = { userId, username }
        this.isLoggedIn = true
        
        // 持久化存储
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify({ userId, username }))
        
        // 获取完整用户信息
        try {
          await this.getUserInfo()
        } catch (error) {
          console.error('获取用户信息失败，但登录成功', error)
        }
        
        return response
      } catch (error) {
        console.error('登录失败', error)
        throw error
      }
    },

    // 注册
    async register(registerForm) {
      try {
        const response = await authApi.register(registerForm)
        return response
      } catch (error) {
        console.error('注册失败', error)
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await authApi.getUserInfo()
        this.userInfo = { ...this.userInfo, ...response }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        return response
      } catch (error) {
        console.error('获取用户信息失败', error)
        throw error
      }
    },

    // 更新用户信息
    async updateUserInfo(userInfo) {
      try {
        const response = await authApi.updateUserInfo(userInfo)
        this.userInfo = { ...this.userInfo, ...response }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        return response
      } catch (error) {
        console.error('更新用户信息失败', error)
        throw error
      }
    },

    // 修改密码
    async changePassword(passwordData) {
      try {
        const response = await authApi.changePassword(passwordData)
        return response
      } catch (error) {
        console.error('修改密码失败', error)
        throw error
      }
    },

    // 登出
    logout() {
      this.token = ''
      this.userInfo = {}
      this.isLoggedIn = false
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
})